package com.example.wyh.bluetoothpro;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import static android.content.ContentValues.TAG;

public class BlueMain extends AppCompatActivity {

    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.blue_main);

        // Init Bluetooth
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices


        String indexString = "";
        if (pairedDevices.size() > 0) {

//            text1.setText("是否获取到："+false);
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                indexString = indexString + device.getName();
//                text1.setText("是否获取到："+pairedDevices);
                // Add the name and address to an array adapter to show in a ListView
//                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                if (device.getName().equals("小米手机")) {
                    Log.i(TAG, device.getName() + "," + device.getAddress());
//                try {
                    OutputStream os;
                    device.connectGatt(this, false, new BluetoothGattCallback() {
                        @Override
                            public void onServicesDiscovered(BluetoothGatt g, int status) {
                            BluetoothGatt gatt = g;
                            BluetoothGattService service = gatt.getService(UUID.fromString("955a1523-0fe2-f5aa-a094-84b8d4f3e8ad"));
                            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("955A1529-0FE2-F5AA-A094-84B8D4F3E8AD"));
                            TextView text1=(TextView) findViewById(R.id.textView);
                            text1.setText("是否获取到：" +":"+characteristic);
//                        characteristic.setValue(new byte[]{1});
//                        gatt.writeCharacteristic(characteristic);
                        }

                        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                            TextView text2=(TextView) findViewById(R.id.textView2);
                            if (newState == BluetoothProfile.STATE_CONNECTED) {
                                Log.i(TAG, "connected");
                                text2.setText("获取到：" +":"+"connected");
                                Boolean isConnected = gatt.discoverServices();
                            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                                Log.i(TAG, "Disconnected from GATT server.");
                                text2.setText("获取到：" +":"+"Disconnected");
                            }
//                            service.getCharacteristic(UUID.fromString("955A1529-0FE2-F5AA-A094-84B8D4F3E8AD"));
//                            gatt.writeCharacteristic()
                        }
                    });
                }
                break;
            }

            TextView text1=(TextView) findViewById(R.id.textView);
            text1.setText("是否获取到：" +":"+indexString);

        }


    }


    class BluetoothServer {
        public BluetoothServer() throws IOException {
        }

        // 要建立一个ServerSocket对象，需要使用adapter.listenUsingRfcommWithServiceRecord方法
        // UUID可以在网上去申请

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();;
        private BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("myServerSocket",
                UUID.fromString("955A1529-0FE2-F5AA-A094-84B8D4F3E8AD"));
        BluetoothSocket socket = serverSocket.accept();

        void m() throws IOException {
            if (socket != null) {
                InputStream inputStream = socket.getInputStream();
                int read = -1;
                final byte[] bytes = new byte[1024];
                for (; (read = inputStream.read(bytes)) > -1;) {
                    final int count = read;
                    Thread _start = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < count; i++) {
                                if (i > 0) {
                                    sb.append(' ');
                                }
                                String _s = Integer.toHexString(bytes[i] & 0xFF);
                                if (_s.length() < 2) {
                                    sb.append('0');
                                }
                                sb.append(_s);
                            }
                            System.out.println(sb.toString());
                        }
                    });
                    _start.start();
                }
            }
        }
    }


    class BluetoothClient {
        BluetoothDevice device = null;

        //通过构造函数来传入一个BluetoothDevice实例
        public BluetoothClient(BluetoothDevice device) {
            this.device = device;
        }
        BluetoothSocket socket = null;
        void connetServer() throws IOException {
            Thread _clientThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        //通过BluetoothDevice实例的createRfcommSocketToServiceRecord方法可以返回一个带有UUID的BluetoothSocket实例
                        socket = device.createRfcommSocketToServiceRecord(UUID.fromString("955A1529-0FE2-F5AA-A094-84B8D4F3E8AD"));
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        socket.connect();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                }
            });
            _clientThread.start();
        }
    }

}

